/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package BancoDeDados;

import Biblioteca.VerificacaoErros;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 * ConexaoFirebird
 * 
 * Versao 1.0
 * 
 * Data Criação 28/01/2014
 *
 * @author Igor
 */
public class ConexaoFirebird implements ConexaoBD {
    //Atributos
    private static ConexaoFirebird uniqueInstance;
    private Connection con = null;
    private Statement stm = null;
    private String driver = "";
    private Path directoryDB;
    private String arquivo;
    private String url = "";
    private String userNameDB = "";
    private String passwordDB = "";

    //Construtores
    public ConexaoFirebird() throws IOException {
        this.gerenciarConfiguracoes();

        try {
            //Path path = Paths.get(arquivo);
            this.directoryDB = Paths.get(arquivo);
            this.directoryDB = this.directoryDB.toRealPath(LinkOption.NOFOLLOW_LINKS);
            Class.forName(this.driver);
            this.con = DriverManager.getConnection(this.url + this.directoryDB.toString(),
                    this.userNameDB,
                    this.passwordDB);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, VerificacaoErros.retornaMensagemErro(e), "Erro!", JOptionPane.ERROR_MESSAGE);
            System.exit(0);
        }
    }

    //Metodos Getters e Setters
    /**
     * @return the con
     */
    public Connection getCon() {
        return con;
    }

    /**
     * @param con the con to set
     */
    public void setCon(Connection con) {
        this.con = con;
    }

    /**
     * @return the stm
     */
    public Statement getStm() {
        return stm;
    }

    /**
     * @param stm the stm to set
     */
    public void setStm(Statement stm) {
        this.stm = stm;
    }

    //Outros Metodos
    /**
     * Preenche os campos de conexao, driver, etc, do Banco de Dados
     */
    public void gerenciarConfiguracoes(){
        Properties config = new Properties();
        String arquivoProperties = "./configTREF.properties";
        try {
            config.load(new FileInputStream(arquivoProperties));
        } catch (IOException ex) {
            Logger.getLogger(ConexaoMySQL.class.getName()).log(Level.SEVERE, null, ex);
        }

        String porta = config.getProperty("Firebird_porta");
        String ipServidor = config.getProperty("Firebird_ipServidor");
        String arquivoBD = config.getProperty("Firebird_baconDeDados");
        String userName = config.getProperty("Firebird_userName");
        String password = config.getProperty("Firebird_password");

        this.driver = "org.firebirdsql.jdbc.FBDriver";
        this.url = "jdbc:firebirdsql:"+ipServidor+"/"+porta+":";
        this.userNameDB = userName;
        this.passwordDB = password;
        //O arquivo encontra-se no mesmo diretoWrio da aplicacao 
        this.arquivo = arquivoBD;
    }
    /**
     * Inicializa conexao com o Banco de Dados
     * @throws Exception 
     */
    public void startDB() throws Exception {
        try {
            setStm(getCon().createStatement());
        } catch (Exception e) {
            throw new IllegalArgumentException(e.getMessage());
        }
    }

    /**
     * Finaliza conexao com o Banco de Dados
     * @throws Exception 
     */
    public void stopDB() throws Exception {
        try {
            getStm().close();
        } catch (Exception e) {
            throw new IllegalArgumentException(e.getMessage());
        }
    }

    @Override
    public void restartDB() throws Exception {
        stopDB();
        startDB();
    }
    
    public static synchronized ConexaoFirebird getInstance() throws IOException{
        if (uniqueInstance == null) {
            uniqueInstance = new ConexaoFirebird();
        }
        return uniqueInstance;
    }
}
